package com.gin.kotlin.gf2gamecommunity.composable

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.gin.kotlin.api.AccountApi
import com.gin.kotlin.form.LoginForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.database.entity.GF2Account
import com.gin.kotlin.response.Res
import com.gin.kotlin.response.account.LoginBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.time.ZonedDateTime

@Composable
fun LoginDialog(
    api: AccountApi = App.INSTANCE.api.accountApi,
    onSuccess: (uid: Int?, token: String?, loginForm: LoginForm) -> Unit = { _, _, _ -> },
    onCloseDialog: () -> Unit
) {
    Dialog(onDismissRequest = { }) {
        Card(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
                .height(240.dp),
            shape = RoundedCornerShape(16.dp),
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(16.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                // 登录按钮可点击
                var clickable by remember { mutableStateOf(true) }
                // 用户名和密码
                var username by remember { mutableStateOf("") }
                var password by remember { mutableStateOf("") }
                // 关闭按钮
                Icon(imageVector = Icons.Filled.Close, contentDescription = "关闭弹窗", modifier = Modifier.clickable { onCloseDialog() })
                // 用户名输入框
                TextField(value = username, onValueChange = { username = it }, label = { Text("手机 或 邮箱") },
                    // 软键盘右下角按钮为“下一个”
                    keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Next))
                // 密码输入框
                TextField(value = password, onValueChange = { password = it },
                    // 密码替换为 * 号
                    visualTransformation = PasswordVisualTransformation(),
                    // 软键盘为密码键盘
                    keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Password), label = { Text("密码") })

                Spacer(Modifier.height(16.dp))
                // 登录按钮
                Button(enabled = clickable, onClick = {
                    clickable = false
                    // 发送登录请求
                    val loginForm = LoginForm(username, password)
                    api.login(loginForm).enqueue(object : Callback<Res<LoginBody>?> {
                        override fun onResponse(p0: Call<Res<LoginBody>?>, response: Response<Res<LoginBody>?>) {
                            clickable = false
                            response.body()?.data?.account?.apply {
                                App.toast("登录成功")

                                // 登录成功后记录到数据库
                                val accountDao = App.INSTANCE.database.gF2AccountDao()
                                val account = GF2Account(
                                    uid = uid!!,
                                    token = token!!,
                                    username = username,
                                    password = loginForm.passwd,
                                    expire = ZonedDateTime.now().plusDays(2),
                                    current = !accountDao.list().any { it.current },
                                    autoSignIn = false,
                                    autoDailyTask = false,
                                    autoExchange = false,
                                )
                                accountDao.add(account)

                                onSuccess(uid, token, loginForm)
                            }
                        }

                        override fun onFailure(p0: Call<Res<LoginBody>?>, throwable: Throwable) {
                            clickable = false
                            App.onFailed(throwable)
                        }
                    })
                }) { Text("登录") }

            }
        }
    }
}